package com.itheima.project.face.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.project.constant.SuperConstant;
import com.itheima.project.constant.security.EnterpriseCacheConstant;
import com.itheima.project.constant.security.EnterpriseConstant;
import com.itheima.project.core.enums.security.EnterpriseEnum;
import com.itheima.project.exception.ProjectException;
import com.itheima.project.face.EnterpriseFace;
import com.itheima.project.init.InitEnterpriseSite;
import com.itheima.project.pojo.Enterprise;
import com.itheima.project.service.IEnterpriseService;
import com.itheima.project.utils.BeanConv;
import com.itheima.project.utils.EmptyUtil;
import com.itheima.project.utils.ExceptionsUtil;
import com.itheima.project.vo.security.EnterpriseVo;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @ClassName EnterpriseFaceImpl.java
 * @Description 企业服务
 */
@Slf4j
@Component
public class EnterpriseFaceImpl implements EnterpriseFace {

    @Autowired
    IEnterpriseService enterpriseService;

    @Autowired
    InitEnterpriseSite initEnterpriseSite;

    @Override
    @Cacheable(value = EnterpriseCacheConstant.PAGE,key ="#pageNum+'-'+#pageSize+'-'+#enterpriseVo.hashCode()")
    public Page<EnterpriseVo> findEnterpriseVoPage(EnterpriseVo enterpriseVo,
                                                   int pageNum,
                                                   int pageSize)throws ProjectException {
        try {
            Page<Enterprise> page = enterpriseService.findEnterpriseVoPage(enterpriseVo, pageNum, pageSize);
            Page<EnterpriseVo> pageVo = BeanConv.toPage(page,EnterpriseVo.class);
            return pageVo;
        } catch (Exception e) {
            log.error("查询企业列表异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(EnterpriseEnum.PAGE_FAIL);
        }
    }

    @Override
    @Caching(evict = {@CacheEvict(value = EnterpriseCacheConstant.PAGE,allEntries = true),
        @CacheEvict(value = EnterpriseCacheConstant.LIST,allEntries = true)})
    @Transactional
    public EnterpriseVo createEnterprise(EnterpriseVo eterperiseVo)throws ProjectException {
        try {
            Enterprise enterpriseResult = enterpriseService.createEnterprise(eterperiseVo);
            //同步缓存
            if (!EmptyUtil.isNullOrEmpty(enterpriseResult)){
                initEnterpriseSite.addWebSiteforRedis(eterperiseVo);
            }
            return BeanConv.toBean(enterpriseResult,EnterpriseVo.class);
        } catch (Exception e) {
            log.error("保存企业异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(EnterpriseEnum.CREATE_FAIL);
        }

    }

    @Override
    @Caching(evict = {@CacheEvict(value = EnterpriseCacheConstant.PAGE,allEntries = true),
        @CacheEvict(value = EnterpriseCacheConstant.LIST,allEntries = true)})
    @Transactional
    public EnterpriseVo updateEnterprise(EnterpriseVo enterpriseVo)throws ProjectException {
        try {
            Boolean flag = enterpriseService.updateEnterprise(enterpriseVo);
            if (flag){
                if (enterpriseVo.getEnableFlag().equals(SuperConstant.YES)){
                    initEnterpriseSite.updataWebSiteforRedis(enterpriseVo);
                }else {
                    initEnterpriseSite.deleteWebSiteforRedis(enterpriseVo);
                }
                return enterpriseVo;
            }else {
                log.error("修改企业异常!");
                throw new ProjectException(EnterpriseEnum.UPDATE_FAIL);
            }
        } catch (Exception e) {
            log.error("修改企业异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(EnterpriseEnum.UPDATE_FAIL);
        }

    }

    @Override
    @Caching(evict = {@CacheEvict(value = EnterpriseCacheConstant.PAGE,allEntries = true),
        @CacheEvict(value = EnterpriseCacheConstant.LIST,allEntries = true)})
    @Transactional
    public Boolean deleteEnterprise(String[] checkedIds)throws ProjectException {
        try {
            //同步缓存
            for (String checkedId : checkedIds) {
                Enterprise enterprise = enterpriseService.getById(checkedId);
                EnterpriseVo enterpriseVo = BeanConv.toBean(enterprise, EnterpriseVo.class);
                initEnterpriseSite.deleteWebSiteforRedis(enterpriseVo);
            }
            return  enterpriseService.deleteEnterprise(checkedIds);
        } catch (Exception e) {
            log.error("删除企业异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(EnterpriseEnum.DELETE_FAIL);
        }
    }

    @Override
    @Cacheable(value =EnterpriseCacheConstant.LIST)
    public List<EnterpriseVo> enterpriseList() throws ProjectException{
        try {
            List<Enterprise> enterprises = enterpriseService.enterpriseList();
            return BeanConv.toBeanList(enterprises,EnterpriseVo.class);
        } catch (Exception e) {
            log.error("删除企业异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(EnterpriseEnum.INIT_ENTERPRISEID_OPTIONS_FAIL);
        }
    }

    @Override
    public List<EnterpriseVo> findEnterpriseVoIsValid() throws ProjectException {
        QueryWrapper<Enterprise> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Enterprise::getEnableFlag, SuperConstant.YES)
                .and(wrapper->wrapper
                        .eq(Enterprise::getStatus, EnterpriseConstant.TRIAL)
                        .or()
                        .eq(Enterprise::getStatus,EnterpriseConstant.OFFICIAL));
        List<Enterprise> list = enterpriseService.list(queryWrapper);
        return BeanConv.toBeanList(list,EnterpriseVo.class);
    }


}
